package com.biscuit.page.basicservice.interceptor;

import com.biscuit.page.basicservice.model.context.RequestContext;
import com.biscuit.page.basicservice.conf.handler.RequestContextHandler;
import com.biscuit.page.basicservice.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author biscuit
 * @createTime 2024/5/18 10:39
 */
@Slf4j
@Component
public class RequestInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        RequestContext context = RequestContextHandler.getContext();
        context.setIp(IpUtil.getIpAddress(request));
        context.setRequest(request);
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        RequestContextHandler.clear();
    }
}
